<?php

namespace app\controller;

use app\general\ApiResponse;
use app\general\utils\ConversionUtils;
use app\model\DictType;
use Carbon\Carbon;
use support\Db;
use support\Request;
use Webman\Captcha\CaptchaBuilder;
use yzh52521\hash\Hash;


class DictTypeController extends BaseController
{

    public function index(Request $request)
    {
        $begin = $request->input('params')['beginTime']??'';
        $end = $request->input('params')['endTime']??'';
        if(!empty($begin)){
            $begin = Carbon::parse($begin)->startOfDay();
        }
        if(!empty($end)){
            $end = Carbon::parse($end)->endOfDay();
        }

        $query = Db::table('dict_type')
            ->when($request->input('dictName'), function ($query) use ($request) {
                return $query->where('dict_name', 'like', '%'.$request->input('dictName').'%');
            })
            ->when($request->input('dict_type'), function ($query) use ($request) {
                return $query->where('dict_type', 'like', '%'.$request->input('dictType').'%');
            })
            ->when($request->input('status'), function ($query) use ($request) {
                return $query->where('status', $request->input('status'));
            })
            ->when($begin, function ($query) use ($begin,$end) {
                return $query->where('create_time', '>=', $begin)
                    ->where('create_time', '<', $end);
            })->paginate($request->get('pageSize'));
        $items = $query->items();
        foreach ($items as $key=>$val){
            $items[$key] = ConversionUtils::underscoreToHump($val) ;
            $items[$key]['createTime'] = Carbon::parse($items[$key]['createTime'])->toIso8601String();
        }
        return  json($this->success('操作成功',$items,$query->total()));
    }

    public function store(Request $request)
    {
        $DictType = new DictType();
        $DictType->setRawAttributes(ConversionUtils::humpToUnderscore($request->all()));
        $DictType->version=0;
        $DictType->save();
        return  json($this->success('操作成功'));
    }

    /**
     * 更新
     * @param Request $request
     * @param $id
     * @return \support\Response
     */
    public function update(Request $request,$id)
    {
        $DictType = DictType::find($id);
        if(empty($DictType)){
            return  json($this->success('操作失败'));
        }
        $data = $request->all();
        $data = ConversionUtils::humpToUnderscore($data);
        unset($data['create_time'],$data['updateTime']);
        $DictType->setRawAttributes($data);
        $DictType->save();
        return  json($this->success('操作成功'));
    }

    public function destroy(Request $request, $id)
    {
        Db::table('movie_basic')->delete($id);
//        $model = $this->getModel($id);
//        $model->delete();
        return  json($this->success('操作成功'));
    }

}
